package com.myblog.controller;

import cn.hutool.core.img.ImgUtil;
import com.myblog.constant.CodeType;
import com.myblog.model.User;
import com.myblog.service.UserService;
import com.myblog.utils.DataMap;
import com.myblog.utils.ImageUtils;
import com.myblog.utils.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.security.Principal;


@Slf4j
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 判断用户是否登录
     * @param request
     * @return
     */
    @GetMapping("/isLogin")
    public String isLogin(HttpServletRequest request){
        try{
            //获取用户姓名
            Principal userPrincipal = request.getUserPrincipal();
            if(userPrincipal == null){
                return JsonResult.fail(CodeType.USER_NOT_LOGIN).toJSON();
            }
            return JsonResult.build().toJSON();

        }catch (Exception e){
            log.error("UserController canYouWrite Excepion",e);
        }
        return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
    }

    @PostMapping("/register")
    public String register(User user){
        try{
            //注册
            DataMap data = userService.register(user);

            return JsonResult.build(data).toJSON();

        }catch (Exception e){
            log.error("UserController register Excepion",user,e);
        }
        return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
    }

    @GetMapping("/canYouWrite")
    public String ifHaveRole(HttpServletRequest request){
        try{
            //获取用户姓名
            Principal userPrincipal = request.getUserPrincipal();
            User user = userService.searchUserByName(userPrincipal.getName());
            //判断用户权限
            DataMap data = userService.ifHavePermission(user.getId());

            return JsonResult.build(data).toJSON();

        }catch (Exception e){
            log.error("UserController canYouWrite Excepion",e);
        }
        return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
    }

    @PostMapping("/getUserPersonalInfo")
    public String getUserPersonalInfo(HttpServletRequest request) {
        try {
            //获取用户姓名
            Principal userPrincipal = request.getUserPrincipal();
            User user = userService.searchUserByName(userPrincipal.getName());
            //判断用户是否为空，如果不为空，者获取信息
            if(user != null){
                String username = user.getUsername();
                DataMap data = userService.getUserPersonInfo(username);
                return JsonResult.build(data).toJSON();
            }
        } catch (Exception e) {
            log.error("UserController getUserPersonalInfo Excepion", e);
        }
        return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
    }

    /**
     * 发送验证码
     * @param phone
     * @param sign
     * @param session
     * @param request
     * @return
     */
    @PostMapping("/getCode")
    public String getCode(@RequestParam(value = "phone")String phone,
                          @RequestParam(value = "sign")String sign,
                          HttpSession session,
                          HttpServletRequest request){
        try {
            DataMap data = userService.sendCode(phone,session);
            return JsonResult.build(data).toJSON();
        } catch (Exception e) {
            log.error("UserController getUserPersonalInfo Excepion", e);
        }
        return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
    }

    /**
     * 修改电话以及密码
     * @param phone
     * @param authCode
     * @param newPassword
     * @return
     */
    @PostMapping(value = "/changePassword",params = "authCode")
    public String changePassword(@RequestParam(value = "phone")String phone,
                                 @RequestParam(value = "authCode")String authCode,
                                 @RequestParam(value = "newPassword")String newPassword,
                                 HttpSession session,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws IOException {
        try {
            //获取用户姓名
            Principal userPrincipal = request.getUserPrincipal();
            User user = userService.searchUserByName(userPrincipal.getName());

            DataMap data = userService.changePhoneAndPassword(phone,newPassword,user.getId(),authCode,session);

            return JsonResult.build(data).toJSON();
        } catch (Exception e) {
            log.error("UserController getUserPersonalInfo Excepion", e);
        }
        return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
    }

    /**
     * 修改电话
     * @param phone
     * @param authCode
     * @param newPhone
     * @return
     */
    @PostMapping(value = "/changePhoneByOldPhone",params = "authCode")
    public String changePhoneByOldPhone(@RequestParam(value = "phone")String phone,
                                 @RequestParam(value = "authCode")String authCode,
                                 @RequestParam(value = "newPhone")String newPhone,
                                 HttpSession session,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws IOException {
        try {
            //获取用户姓名
            Principal userPrincipal = request.getUserPrincipal();
            User user = userService.searchUserByName(userPrincipal.getName());

            DataMap data = userService.changePhoneByOldPhone(phone,newPhone,user.getId(),authCode,session);

            return JsonResult.build(data).toJSON();
        } catch (Exception e) {
            log.error("UserController getUserPersonalInfo Excepion", e);
        }
        return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
    }

    /**
     * 忘记密码修改密码
     * @param phone
     * @param newPassword
     * @return
     */
    @PostMapping("/changePassword")
    public String changePassword(@RequestParam(value = "phone")String phone,
                                 @RequestParam(value = "newPassword")String newPassword,
                                 HttpSession session,
                                 HttpServletRequest request){
        try {

            DataMap data = userService.forgetChangePhoneAndPassword(phone,newPassword,session);
            return JsonResult.build(data).toJSON();
        } catch (Exception e) {
            log.error("UserController getUserPersonalInfo Excepion", e);
        }
        return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
    }

    /**
     * 保存用户信息
     * @param user
     * @param request
     * @return
     */
    @PostMapping("/savePersonalDate")
    public String savaPersonInfo(User user,HttpServletRequest request){
        try {
            //获取用户姓名
            Principal userPrincipal = request.getUserPrincipal();
            if (userPrincipal == null){
                return JsonResult.fail(CodeType.USER_NOT_LOGIN).toJSON();
            }
            DataMap data = userService.saveUserByUserName(userPrincipal.getName(),user);
            return JsonResult.build(data).toJSON();
        } catch (Exception e) {
            log.error("UserController getUserPersonalInfo Excepion", e);
        }
        return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
    }

    /**
     * 更改用户头像
     * @param img
     * @param request
     * @return
     */
    @PostMapping("/uploadHead")
    public String uploadHead(@RequestParam("img") String img,HttpServletRequest request){
        try {
            //通过本项目的ImageUtil将Base64图片格式转化为MultipartFile格式
            MultipartFile imgFile = ImageUtils.base64ToMultipartFile(img);
            //获取用户姓名
            Principal userPrincipal = request.getUserPrincipal();
            if (userPrincipal == null){
                return JsonResult.fail(CodeType.USER_NOT_LOGIN).toJSON();
            }
            User user = userService.searchUserByName(userPrincipal.getName());
            DataMap data = userService.changeUserImgByUsername(user,imgFile);
            return JsonResult.build(data).toJSON();
        } catch (Exception e) {
            log.error("UserController getUserPersonalInfo Exception", e);
        }
        return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
    }

}
